package com.example.demodatajapmapper.service;

import com.example.demodatajapmapper.dao.AccountRepository;
import com.example.demodatajapmapper.dao.CustomerRepository;
import com.example.demodatajapmapper.entity.Account;
import com.example.demodatajapmapper.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AccountService {
    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private AccountRepository accountRepository;

    public Account save(Long customerId, Account account){
        return customerRepository.findById(customerId).map(
                customer -> {
                    account.setCustomer(customer);
                    return accountRepository.save(account);
                }
        ).orElseThrow(() -> new RuntimeException("Customer [customerId=" + customerId + "] can't be found"));
    }

    public Page<Account> findAll(Long customerId, Pageable pageable){
        return accountRepository.findByCustomerCustomerId(customerId, pageable);
    }

    public ResponseEntity<?> deleteAccount(Long customerId, Long accountId){
        if (!customerRepository.existsById(customerId)){
            throw new RuntimeException("Customer [customerId="+customerId+"] can't be found");
        }
        return accountRepository.findById(accountId).map(
                account -> {
                    accountRepository.delete(account);
                    return ResponseEntity.ok().build();
                }
        ).orElseThrow(() -> new RuntimeException("Account [accountId=" + accountId + "] can't be found"));
    }

    public ResponseEntity<Account> updateAccount(Long customerId, Long accountId, Account newAccount){
        Customer customer = customerRepository.findById(customerId).orElseThrow(
                () -> new RuntimeException("Customer [customerId=" + customerId + "]can't be found")
        );
        return accountRepository.findById(accountId).map(
                account -> {
                    newAccount.setCustomer(customer);
                    accountRepository.save(newAccount);
                    return ResponseEntity.ok(newAccount);
                }
        ).orElseThrow(() -> new RuntimeException("Account [accountId=" + accountId + "] can't be found"));
    }
}
